import { sysDictList } from '@/services/common';
import {
  deviceParamsList,
  deviceTypeAdd,
  deviceTypeUpdate,
  monitorLimitsList,
} from '@/services/deviceMsg';
import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, Col, Form, Input, message, Row, Select } from 'antd';
import React, { useImperativeHandle, useState } from 'react';

const ItemOption = React.forwardRef((props: any, ref) => {
  const { refreshList } = props;
  const [form] = Form.useForm<any>();
  const [searchMonitorLimitsform] = Form.useForm<any>();
  const [modalOpen, setModalOpen] = useState(false);
  const [modItem, setModItem] = useState<any>(null);
  const [sysDictListData, setSysDictListData] = useState<any>([]);
  const [tempMonitorLimitsList, setTempMonitorLimitsList] = useState<any>([]);
  const [deviceParamList, setDeviceParamList] = useState<any>([]);

  const handleModalShow = async (row?: any) => {
    if (!modalOpen) {
      getSearchList();
      form.resetFields();
    }
    setModalOpen(!modalOpen);
    searchMonitorLimitsform.resetFields();
    setModItem(row || null);
    if (row?.monitorLimitsList) {
      setTempMonitorLimitsList(
        row.monitorLimitsList.map((its: any) => {
          return {
            value: its.id,
            label: its.itemName,
          };
        }),
      );

      form.setFieldsValue({
        ...row,
        monitorLimitsId: row.monitorLimitsId
          ? row.monitorLimitsId.split(',')
          : [],
        deviceParamIds: row.deviceParamIds
          ? row.deviceParamIds.split(',')
          : [],
      });
    }
  };
  const onSearchMonitorLimits = async () => {
    const res = await monitorLimitsList({
      pageSize: 1000,
      pageNum: 1,
      ...searchMonitorLimitsform.getFieldsValue(),
    });
    if (res?.code === 200) {
      const temp = res.rows.map((its: any) => {
        return {
          value: its.id,
          label: its.itemName,
        };
      });
      setTempMonitorLimitsList(temp);
    }
  };
  const getSearchList = async () => {
    const res = await sysDictList({
      pageSize: 1000,
      pageNum: 1,
      itemClass: 'ageArea',
    });
    if (res?.code === 200) {
      const data = res.rows.map((its: any) => {
        return {
          label: its.itemName,
          value: its.itemValue,
        };
      });
      setSysDictListData(data);
    }

    const deviceParamsres = await deviceParamsList({
      pageSize: 1000,
      pageNum: 1,
    });
    if (deviceParamsres?.code === 200) {
      setDeviceParamList(
        deviceParamsres.rows.map((its: any) => {
          return {
            label: its.paramName,
            value: its.id,
          };
        }),
      );
    }
  };
  useImperativeHandle(ref, () => ({
    handleModalShow,
  }));
  return (
    <ModalForm
      title={modItem?.id ? '修改设备类型' : '新增设备类型'}
      width={600}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnHidden: true,
        onCancel: handleModalShow,
        centered: true,
        maskClosable: false,
      }}
      open={modalOpen}
      submitter={{
        render: (props) => {
          let optBtns: any = [
            <Button
              className="base-button"
              key="cancel"
              onClick={handleModalShow}
            >
              取消
            </Button>,
            <Button
              className="base-button"
              type="primary"
              key="submit"
              onClick={() => props.form?.submit?.()}
            >
              确定
            </Button>,
          ];
          return optBtns;
        },
      }}
      onFinish={async (values) => {
        const sendData = {
          ...values,
          monitorLimitsId: values?.monitorLimitsId
            ? values.monitorLimitsId.join(',')
            : '',
          deviceParamIds: values?.deviceParamIds
            ? values.deviceParamIds.join(',')
            : '',
        };
        let res = null;
        if (modItem?.id) {
          //编辑
          res = await deviceTypeUpdate({
            ...sendData,
            id: modItem.id,
          });
        } else {
          //添加
          res = await deviceTypeAdd(sendData);
        }
        if (res?.code === 200) {
          message.success('操作成功');
          refreshList();
          setModalOpen(false);
        }
        return true;
      }}
    >
      <Row gutter={20}>
        <Col span={12}>
          <ProFormText
            name="name"
            label="设备类型名称"
            fieldProps={{
              maxLength: 100,
              showCount: true,
            }}
            rules={[
              {
                required: true,
                message: '请输入设备类型名称',
              },
            ]}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name="typeValue"
            label="设备类型值"
            min={1}
            max={100}
            fieldProps={{ precision: 0 }}
            rules={[
              {
                required: true,
                message: '请输入设备类型值',
              },
            ]}
          />
        </Col>
      </Row>
      <Row
        gutter={20}
        style={{ marginBottom: 6, color: '#999999', fontSize: 12 }}
      >
        <Col span={24}>
          <span>根据如下筛选项进行筛选报警限</span>
        </Col>
      </Row>
      <Row gutter={20} style={{ marginBottom: 16 }}>
        <Col span={24}>
          <Form
            layout="inline"
            form={searchMonitorLimitsform}
            onValuesChange={onSearchMonitorLimits}
          >
            <Form.Item label="年龄区间" name="ageArea">
              <Select
                style={{ width: 180 }}
                placeholder="年龄区间"
                options={sysDictListData}
                allowClear
              />
            </Form.Item>
            <Form.Item label="性别" name="sex">
              <Select
                style={{ width: 140 }}
                placeholder="性别"
                allowClear
                options={[
                  {
                    label: '男',
                    value: '1',
                  },
                  {
                    label: '女',
                    value: '2',
                  },
                ]}
              />
            </Form.Item>
            <Form.Item
              label="报警限编码"
              name="itemCode"
              style={{ marginRight: 0 }}
            >
              <Input
                style={{ width: 208 }}
                placeholder="报警限编码"
                allowClear
              />
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={24}>
          <ProFormSelect
            name="monitorLimitsId"
            label="选择报警限"
            placeholder="请选择报警限"
            mode="multiple"
            options={tempMonitorLimitsList}
          />
        </Col>
      </Row>
      <Row gutter={20}>
        <Col span={24}>
          <ProFormSelect
            name="deviceParamIds"
            label="选择关联属性"
            placeholder="选择关联属性"
            mode="multiple"
            options={deviceParamList}
          />
        </Col>
      </Row>
    </ModalForm>
  );
});

export default ItemOption;
